package com.ruoyi.common.utils.http.ftp.pool;


import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.ftp.node.Node;
import com.ruoyi.common.utils.http.ftp.node.impl.DirNode;
import com.ruoyi.common.utils.http.ftp.node.impl.FileNode;
import com.ruoyi.common.utils.http.ftp.node.impl.MixedNode;
import org.apache.commons.net.ftp.FTPClient;

import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Component;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import java.util.ArrayList;
import java.util.Arrays;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

@Component
public class FTPTemplate {

    private static  final Logger logger = LoggerFactory.getLogger(FTPTemplate.class);
    private FTPClient ftpClient;

    public MixedNode listFile(String dir) throws Exception {
        ftpClient=null;
        try {
            ftpClient=FTPClientFactory.getFtpClientPool().borrowObject();
            MixedNode list = list(dir);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            FTPClientFactory.getFtpClientPool().returnObject(ftpClient);
        }
    }

    private  MixedNode list(String dir) throws IOException {
        if(!dir.startsWith(Constants.URLPath_SPLIT)){
            dir=Constants.URLPath_SPLIT+dir;
        }
        if(!dir.endsWith(Constants.RESOURCE_PREFIX)){
            dir=dir+Constants.URLPath_SPLIT;
        }
        //dir=new String(dir.getBytes("GBK"),"utf-8");
        List<Node> contents=new ArrayList<>();
        for (FTPFile ftpFile:ftpClient.listFiles(dir)) {
            if(ftpFile.getName().equals(".")||ftpFile.getName().equals("..")) continue;
            if(ftpFile.isDirectory()){
                new DirHandler().handleNode(dir +ftpFile.getName()+Constants.URLPath_SPLIT,contents);
            }else{
                FileNode fileNode=new FileNode(ftpFile.getName(),ftpFile.getSize(),ftpFile.getTimestamp().getTime().getTime());
                contents.add(fileNode);
            }
        }
        return new MixedNode(contents);
    }

    public boolean uploadFile(String remotePath,List<File> fileList) throws Exception {
        try {
            ftpClient=FTPClientFactory.getFtpClientPool().borrowObject();
            // 验证FTP服务器是否登录成功
//            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
//                throw new IOException("ftp登录失败");
//            }
            boolean upload = upload(remotePath, fileList);
            return  upload;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            FTPClientFactory.getFtpClientPool().returnObject(ftpClient);
        }
    }


    private boolean upload(String remotePath, List<File> fileList) throws IOException {
        FileInputStream fis=null;
        try {
            //ftpClient.setControlEncoding("UTF-8");
            //remotePath=new String(remotePath.getBytes("GBK"),"iso-8859-1");
            boolean workingDirectory = ftpClient.changeWorkingDirectory(remotePath);
            if(!workingDirectory){
                ftpClient.changeWorkingDirectory("/");
                workingDirectory=ftpClient.changeWorkingDirectory(remotePath);
                if(!workingDirectory){
                    logger.error("ftp路径不存在");
                    return  false;
                }
            }
            //ftpClient.makeDirectory(remotePath);
            //ftpClient.changeWorkingDirectory(remotePath);
            ftpClient.setBufferSize(1024);
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            for(File fileItem : fileList){
                fis = new FileInputStream(fileItem);
                ftpClient.storeFile(fileItem.getName(),fis);
                //ftpClient.storeFile(new String(fileItem.getName().getBytes("GBK"),"iso-8859-1"),fis);
            }

        } catch (IOException e) {
            logger.error("上传文件异常",e);
            e.printStackTrace();
            return false;
        } finally {
            if(fis!=null){
                fis.close();
            }
        }
        return true;
    }
    private class DirHandler  {
        public DirHandler() {
            // Prevent Synthetic Access
        }
        public void handleNode(String dir, List<Node> targetContents) throws IOException {
            MixedNode mixedSqlNode = list(dir);
            String[] split = dir.split(Constants.URLPath_SPLIT);
            String name="";
            for(int i=split.length-1;i>0;i--){
                if(StringUtils.isNotEmpty(split[i])){
                    name=split[i];
                    break;
                }
            }
            DirNode DirNode = new DirNode(mixedSqlNode,name);
            targetContents.add(DirNode);
        }
    }
}

